from flask import Flask
from flask import render_template,request,redirect,url_for
from flask_bootstrap import Bootstrap
from utils.dataManager import Data_Collector,Beat_Response_Table
from utils.dataManager import check_ping
import json
import cv2

'''
Step1:
@Introduction: 初始化
Flask类的构造函数只有一个必须指定的参数，即程序主模块或包的名字。在大多数程序中，Python 的 __name__ 变量就是所需的值。
'''
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'  #设置 Flask-WTF
data_manager = Data_Collector()

'''数据保存管理类'''
@app.route("/")
def clickTest():
    return render_template("code002_clickClock1.html")

'''开始采集数据: 提示音提醒 + 响应节拍回显'''
@app.route("/start/<time>")
def start_collected(time):
    '''
    :return: 返回指定提示音编号
    '''
    print("start")
    if(time != "00:00:00"):
        res = data_manager.generateBeat()
        if(res == None):
            return ""
        else:
            print(f"res={res}")
            return str(res)
    else:
        data_manager.w_index = 0
        data_manager.beat_table = Beat_Response_Table()  #未开始计时，则初始化data_manager中的beat_table
        return ""

'''暂停采集数据: 关闭提示音提醒 + 关闭节拍响应回显'''
@app.route("/pause")
def pause_collected():
    print("pause")
    return ""

'''结束采集数据: 保存数据 + 返回折线图要求的输入数据'''
@app.route("/end")
def end_collected():
    print("end")
    #保存视频
    data_manager.SAVE_VIDEO_FLAGs = [False] * len(data_manager.SAVE_VIDEO_FLAGs)

    # 处理并保存数据
    df = data_manager.save_beat_response()
    # 将df转化成符合折线图绘制的数据格式
    x_columns = ['beat_startT','beat_responeT']
    y_columns = ['beat_key','beat_resKey']
    # df = data_manager.preProcess(df,y_columns)
    # 先将空值全部转化为None
    df = df.fillna("None")
    x_axis,y_axis = data_manager.df_2_lineChart(df,x_columns,y_columns)

    # 绘制曲线
    label_names = ['real','response']
    # data_manager.beat_response_lineChart_plot(x_axis,y_axis,label_names=label_names)
    # res_json = "{ \"x_axis\" : "
    res_json = ""
    res_json += json.dumps(x_axis) + "_json_"
    res_json += json.dumps(y_axis) + "_json_"
    res_json += json.dumps(label_names)

    # 结束计时，初始化data_manager中的beat_table
    data_manager.beat_table = Beat_Response_Table()
    return res_json

'''按键响应处理, 获取最新10条响应数据进行回显'''
@app.route("/keyPress/<key>")
def keyPress(key):
    print(f"keyPress = {key}")
    data_manager.beatRespone(key)
    table_json = data_manager.get_BeatTable(10)
    print(table_json)
    return table_json

'''实时获取疲劳状态'''
@app.route("/getFatigue")
def getFatigue():
    state = data_manager.fatigue_judgement()
    print(f"state = {state}")
    return state

'''实时采集视频数据(待keyPress处理之后)'''
@app.route("/save_monitor_video/<ip>")
def save_monitor_video(ip):
    '''
    :param addr: 0表示本地摄像头，还可以是rtsp地址
    :return:
    '''
    if(ip != "0"):
        #ping一下ip是否可通
        info, res = check_ping(ip)
        if(res == True):
            rtsp = "rtsp://admin:zhangdeping1@" + ip + ":554/h264/ch1/main/av_stream"
            camera = cv2.VideoCapture(rtsp,cv2.CAP_DSHOW)
            data_manager.SAVE_VIDEO_FLAGs.append(True)
            data_manager.save_monitorVideo(camera, ip)
        else:
            return "res"
    else:
        camera = cv2.VideoCapture(0,cv2.CAP_DSHOW)
        data_manager.SAVE_VIDEO_FLAGs.append(True)
        data_manager.save_monitorVideo(camera,"0")  #本地摄像头
    return ""

'''手动标注视频（KSS量表）'''
@app.route("/annotate_Fatigue", methods=['post'] )
def annotate_Fatigue():
    form = request.form
    fatigue_id = form['fatigueState']
    data_manager.hand_annotate_fatigue(fatigue_id)
    return redirect(url_for("clickTest"))

'''
初始化 Flask-Bootstrap
'''
bootstrap = Bootstrap(app)

'''
Step3:
@Introduction：启用服务器
'''
if __name__ == '__main__':
    app.run(debug=True,threaded=True)
